package edu.siu.math.egut.main;

import java.util.Scanner;

import edu.siu.math.egut.io.Algorithms;
import edu.siu.math.egut.util.Group;
import edu.siu.math.egut.util.NotARootException;
import edu.siu.math.egut.util.Sunipotent;
import edu.siu.math.egut.util.Unipotent;


public class Commutator {

    /**
     * @param args
     */
    public static void main(String[] args) {
	if(args.length==2){
	    try {
		doCommutator(args[0],args[1]);
		} catch (NumberFormatException e) {
		    System.out.println("Problem with one of the roots entered.");
		    e.printStackTrace();
		} catch (NotARootException e) {
		    System.out.println("Problem with one of the roots entered.");
		    e.printStackTrace();
		}
	}
	else if(args.length==0){
	    Scanner scanner = new Scanner( System.in);
	    String a = scanner.next();
	    if(Algorithms.QUIT.matcher(a).matches())
		System.exit(0);
	    String b = scanner.next();
	    if(Algorithms.QUIT.matcher(b).matches())
		System.exit(0);
	    while( !Algorithms.QUIT.matcher(a).matches() 
		    && !Algorithms.QUIT.matcher(b).matches()){
		
		try {
		    doCommutator(a,b);
		} catch (NumberFormatException e) {
		    System.out.println("Problem with one of the roots entered.");
		    e.printStackTrace();
		} catch (NotARootException e) {
		    System.out.println("Problem with one of the roots entered.");
		    e.printStackTrace();
		}
		    a = scanner.next();
		    if(!Algorithms.QUIT.matcher(a).matches())
			b = scanner.next();

	    }
	    
	}
	else 
	    System.out.println("Need 0 or 2 args; have "+args.length+".");

    }

    private static void doCommutator(String string, String string2) throws NumberFormatException, NotARootException {
	doCommutator(edu.siu.math.egut.io.Algorithms.rootFromString(string),edu.siu.math.egut.io.Algorithms.rootFromString(string2));
    }

    private static void doCommutator(int[] a, int[] b) {
	Group g = Group.getGroup(a.length);
	StringBuilder sb = new StringBuilder("x_{");
	sb.append(Algorithms.tupleToShortString(a));
	sb.append("}(r).x_{");
	sb.append(Algorithms.tupleToShortString(b));
	sb.append("}(s).x_{");
	sb.append(Algorithms.tupleToShortString(a));
	sb.append("}(-r).x_{");
	sb.append(Algorithms.tupleToShortString(b));
	sb.append("}(-s)=");
	sb.append( new Unipotent(g,g.commutator(Sunipotent.create(a, "r"),Sunipotent.create(b, "s"))));
	System.out.println(sb.toString());
	
    }

 
}
